package com.dmcloud.dm.auth.config;

import com.dmcloud.dm.auth.Exception.MyOAuth2WebResponseExceptionTranslator;
import com.dmcloud.dm.auth.service.DmClientDetailsService;
import com.dmcloud.common.constant.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaodao
 * date: 2019/11/1
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public TokenStore tokenStore;
    @Autowired
    public JwtAccessTokenConverter jwtAccessTokenConverter;

    @Resource(name = "dMJwtTokenEnhancer")
    private TokenEnhancer DMJwtTokenEnhancer;

    @Autowired
    private MyOAuth2WebResponseExceptionTranslator myOAuth2WebResponseExceptionTranslator;

    /**
     * 第三方信息
     * 去数据库中查找
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        DmClientDetailsService clientDetailsService = new DmClientDetailsService(dataSource);
        clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
        clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
        clients.withClientDetails(clientDetailsService);
    }

    /**
     * 端点配置
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                //这个4种模式的认证
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore)
                .tokenEnhancer(jwtAccessTokenConverter)
                //这个是refresh用的
                .userDetailsService(userDetailsService)
                .exceptionTranslator(myOAuth2WebResponseExceptionTranslator)
//                .tokenServices(tokenServices());//自定义token过期时间

        ;
        if (jwtAccessTokenConverter != null) {
            TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
            List<TokenEnhancer> tokenEnhancerList = new ArrayList<>();
            tokenEnhancerList.add(DMJwtTokenEnhancer);//做增强
            tokenEnhancerList.add(jwtAccessTokenConverter);//做转换jwt
            tokenEnhancerChain.setTokenEnhancers(tokenEnhancerList);

            endpoints.tokenEnhancer(tokenEnhancerChain)
                    //经过认证的服务才能拿到tokenkey =jwtkey
                    .accessTokenConverter(jwtAccessTokenConverter);

        }
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer
                .allowFormAuthenticationForClients()
                //访问token_key的用户必须身份认证
                .tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("isAuthenticated()");
    }

    @Primary
    @Bean
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices services = new DefaultTokenServices();
        services.setAccessTokenValiditySeconds(60);//设置20秒过期
        services.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);//设置刷新token的过期时间
        services.setTokenStore(tokenStore);
        return services;
    }


}
